<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="dictData['md_order_status']" v-model="search.status" placeholder="请选择" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item label="产品名称" prop="productTitle">
            <el-input v-model="search.productTitle" class="w150" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="产品分类" prop="productCategory">
            <md-dict-select :options="dictData['md_product_category']" v-model="search.status" placeholder="请选择" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="userEmail">
            <el-input v-model="search.userEmail" class="w150" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" :prems="['web:order:query']" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="success" size="small" plain :prems="['web:order:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单编号" align="center" prop="orderId" min-width="100" />
        <el-table-column label="下单用户" align="center" prop="userEmail" min-width="200" />
        <el-table-column label="下单产品" align="left" prop="productPicture" width="480">
          <template slot-scope="{ row }">
            <div class="product">
              <div class="pic">
                <el-image class="md-image" v-if="row.productPicture && row.productPicture.length>0" :src="row.productPicture[0]" :preview-src-list="row.productPicture" lazy />
              </div>

              <div class="info">
                <md-dict-tag :options="dictData['md_product_category']" :props="{ label: 'dictLabel', value: 'dictValue' }" :value="row.productCategory" />
                <br />
                {{row.productTitle}}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="{ row }">
            <md-dict-tag :options="dictData['md_order_status']" :props="{ label: 'dictLabel', value: 'dictValue' }" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="{ row }">
            <md-button size="mini" type="text" icon="el-icon-search" :prems="['web:order:edit']" @click="handleOrderDetail(row)">详情</md-button>
            <md-button size="mini" type="text" icon="el-icon-user" :prems="['web:order:edit']" v-if="['2','3'].includes(row.status)" @click="handleOrderAuth(row)">审核</md-button>
            <md-button size="mini" type="text" icon="el-icon-truck" :prems="['web:order:edit']" v-if="['4'].includes(row.status)" @click="handleOrderShip(row)">发货</md-button>
            <md-button size="mini" type="text" icon="el-icon-position" :prems="['web:order:edit']" v-if="['5'].includes(row.status)" @click="handleOrderConfirm(row)">确认收货/完成订单</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['web:order:remove']" @click="handleDelete(row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 订单详情 -->
    <md-order-detail-dialog ref="mdOrderDetailDialog" :data="dialog.data" @refresh="getTableDataList" />

    <!-- 审核 -->
    <md-order-audit-dialog ref="mdOrderAuditDialog" :data="dialog.data" @refresh="getTableDataList" />

    <!-- 发货 -->
    <md-order-ship-dialog ref="mdOrderShipDialog" :data="dialog.data" @refresh="getTableDataList" />

    <!-- 收货地址 -->
    <md-order-confirm-dialog ref="mdOrderConfirmDtalog" :data="dialog.data" @refresh="getTableDataList" />
  </md-main>
</template>

<script>
import { listPageProductOrder, delProductOrder } from '@/api/web/product.order.service.js'
import { checkUserExperiencerByUserId } from '@/api/web/user.experiencer.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
import MdOrderDetailDialogComponent from './orderDetailDialog.vue'
import MdOrderAuditDialogComponent from './orderAuditDialog.vue'
import MdOrderShipDialogComponent from './orderShipDialog.vue'
import MdOrderConfirmDialogComponent from './orderConfirmDialog.vue'
export default {
  name: 'MdWebApplyComponent',
  components: {
    'md-order-detail-dialog': MdOrderDetailDialogComponent,
    'md-order-audit-dialog': MdOrderAuditDialogComponent,
    'md-order-ship-dialog': MdOrderShipDialogComponent,
    'md-order-confirm-dialog': MdOrderConfirmDialogComponent
  },
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: { ...searchParams },
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 列表数据，总条数
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 弹窗
      dialog: {
        data: undefined
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['md_order_status', 'md_product_category']).then(res => {
      this.dictData = res
    })
    this.getTableDataList()
  },
  methods: {
    /** 获取数据 */
    async getTableDataList () {
      this.tableLoading = true
      try {
        const res = await listPageProductOrder(this.search)

        const data = res.data.items

        if (data && data.length > 0) {
          data.forEach(item => {
            if (item.productPicture) {
              item.productPicture = JSON.parse(item.productPicture)
            }

            if (item.productThumPicture) {
              item.productThumPicture = JSON.parse(item.productThumPicture)
            }
          })
        }

        this.tableData = data
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.orderId })
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageNum = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    /** 删除 */
    async handleDelete (row) {
      try {
        const ids = row?.orderId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delProductOrder(ids)

        this.$message.success('删除成功')

        this.getTableDataList()
      } catch (error) {
        console.log(error)
      }
    },
    /** 订单详情 */
    async handleOrderDetail (row) {
      try {
        const res = await checkUserExperiencerByUserId(row.userId)

        this.dialog.data = { ...row, experiencerUser: res.data }

        this.$refs.mdOrderDetailDialog.handleOpen()
      } catch (error) {
        console.log(error)
      }

    },
    /** 订单审核 */
    handleOrderAuth (row) {
      this.$refs.mdOrderAuditDialog.handleOpen()

      this.dialog.data = { ...row }
    },
    /** 订单发货 */
    handleOrderShip (row) {
      this.$refs.mdOrderShipDialog.handleOpen()

      this.dialog.data = { ...row }
    },
    /** 订单完成 */
    handleOrderConfirm (row) {
      this.$refs.mdOrderConfirmDtalog.handleOpen()

      this.dialog.data = { ...row }
    }
  }
}

const searchParams = {
  status: undefined,
  productTitle: undefined,
  productCategory: undefined,
  userEmail: undefined,
  userName: undefined,
  userNick: undefined,
  userType: undefined,
  userSex: undefined,
  userPhone: undefined,
  addressCountry: undefined,
  addressProvince: undefined,
  addressCity: undefined,
  addressDistrict: undefined,
  addressName: undefined,
  addressEmail: undefined,
  addressZipCode: undefined,
  beginDate: undefined,
  endDate: undefined,
  createBy: undefined,
  updateBy: undefined,
  pageIndex: 1,
  pageSize: 10,
  orderBy: 'create_time',
  isDesc: true
}
</script>

<style lang="less" scoped>
.product {
  display: flex;
  align-items: center;
  .pic {
    .md-image {
      border: 1px solid #eee;
      border-radius: 6px;
    }
  }
  .info {
    flex: 1;
    padding-left: 20px;

    p {
      font-size: 14px;
      margin-bottom: 10px;
    }
  }
}
</style>